package com.hcms.admin.security;

import com.hcms.admin.service.ISysAdminService;
import com.hcms.mybatis.entity.SysAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class AdminUserDetailsService implements UserDetailsService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISysAdminService sysAdminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("Run loadUserByUsername(), username: {}", username);
        SysAdmin admin = sysAdminService.getAdminByUsername(username, false);
        if (admin == null) {
            logger.error("The username does not exist");
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 获取用户权限
        logger.info("Gets a collection of user permissions");
        Collection<String> permissions = sysAdminService.getPermissionsByAdminId(admin.getId(), false);
        return new AdminUserDetails(admin, permissions);
    }

}
